package com.dbflow5.provider;

import com.dbflow5.config.FlowManager;
import com.dbflow5.database.DatabaseWrapper;
import com.dbflow5.database.FlowCursor;
import com.dbflow5.query.OperatorGroup;
import com.dbflow5.structure.BaseModel;
import ohos.aafwk.ability.DataAbilityRemoteException;

/**
 * Description: Provides a base implementation of a [Model] backed
 * by a content provider. All operations sync with the content provider in this app from a [ContentProvider]
 */
public abstract class BaseSyncableProviderModel extends BaseModel implements ModelProvider {
    public BaseSyncableProviderModel() {
        super();
    }

    @Override
    public boolean save(DatabaseWrapper wrapper) throws DataAbilityRemoteException {
        boolean isSuccess;
        if (exists(wrapper)) {
            isSuccess = ContentUtils.update(FlowManager.contentResolver(), updateUri(), this) > 0;
        } else {
            isSuccess = ContentUtils.insert(FlowManager.contentResolver(), insertUri(), this) > 0;
        }
        return super.save(wrapper) && isSuccess;
    }

    @Override
    public boolean delete(DatabaseWrapper wrapper) throws DataAbilityRemoteException {
        return super.delete(wrapper) && ContentUtils.delete(FlowManager.contentResolver(), deleteUri(), this) > 0;
    }

    @Override
    public boolean update(DatabaseWrapper wrapper) throws DataAbilityRemoteException {
        return super.update(wrapper) && ContentUtils.update(FlowManager.contentResolver(), updateUri(), this) > 0;
    }

    @Override
    public long insert(DatabaseWrapper wrapper) throws DataAbilityRemoteException {
        long rowId = super.insert(wrapper);
        ContentUtils.insert(FlowManager.contentResolver(), insertUri(), this);
        return rowId;
    }

    @Override
    public <T> T load(DatabaseWrapper databaseWrapper) throws DataAbilityRemoteException {
        return (T)load(modelAdapter.getPrimaryConditionClause(this), "", databaseWrapper);
    }

    @Override
    public <T> T load(OperatorGroup whereOperatorGroup, String orderBy, DatabaseWrapper wrapper, String... columns) throws DataAbilityRemoteException {
        FlowCursor cursor = ContentUtils.query(FlowManager.contentResolver(),
                queryUri(), whereOperatorGroup, orderBy, columns);
        if (cursor != null) {
            if (cursor.goToFirstRow()) {
                T model = (T)modelAdapter.loadFromCursor(cursor, wrapper);
                cursor.close();
                return model;
            }
        }
        return null;
    }
}
